/**
 * Created by 丸子 on 2018/7/1.
 */
import Vue from 'vue'
import Base64 from './base64'

// url中获取参数
export function getQueryString (name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}
export function verifyCard (card) {
  const isCard = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(card) || /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$/.test(card)
  // console.log('card:', card, isCard)
  return isCard
}

// 时间转换yyyy-MM-dd hh:mm
export function formatDate (time, fmt = 'yyyy-MM-dd hh:mm') {
  const date = new Date(time)
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

export function debounce (func, wait, immediate) {
  let timeout
  return function () {
    let context = this
    let args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    }, wait)
    if (immediate && !timeout) func.apply(context, args)
  }
}
/**
 * 过滤掉对象为空的键值
 * @param obj
 */
export function filterObjectNullValue (obj) {
  var newObj = {}
  var keys = Object.keys(obj)
  keys.forEach(function (key) {
    var value = obj[key]
    if (value != null) {
      newObj[key] = value
    }
  })
  return newObj
}

// Opera 8.0+
export const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0
Vue.prototype.$isOpera = isOpera

// Firefox 1.0+
export const isFirefox = typeof InstallTrigger !== 'undefined'
Vue.prototype.$isFirefox = isFirefox

// Safari 3.0+ "[object HTMLElementConstructor]"
export const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) {
  return p.toString() === '[object SafariRemoteNotification]'
})(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification))
Vue.prototype.$isSafari = isSafari

// Internet Explorer 6-11
export const isIE = /* @cc_on!@ */false || !!document.documentMode
Vue.prototype.$isIE = isIE

// Edge 20+
export const isEdge = !isIE && !!window.StyleMedia
Vue.prototype.$isEdge = isEdge

// Chrome 1+
export const isChrome = !!window.chrome && !!window.chrome.webstore
Vue.prototype.$isChrome = isChrome

// Blink engine detection
export const isBlink = (isChrome || isOpera) && !!window.CSS
Vue.prototype.$isBlink = isBlink

export function injectVueContext (context) {
  Object.assign(Vue.prototype, context)
}

function getStorageItem (name = 'localStorage', key, defaultValue, encode = true) {
  if (name in window) {
    let item = window[name].getItem(key)
    if (item) {
      try {
        item = encode ? Base64.decode(item) : item
        return JSON.parse(item)
      } catch (e) {
        // console.error(e)
        return
      }
    }
    return item
  }
  return defaultValue
}

export function setStorageItem (name = 'localStorage', key, value, encode = true) {
  if (name in window) {
    let targetValue = value
    if (value) {
      const item = JSON.stringify(value)
      targetValue = encode ? Base64.encode(item) : item
    }
    window[name].setItem(key, targetValue || '')
  }
}

export const getSessionStorageItem = getStorageItem.bind(null, 'sessionStorage')

export const setSessionStorageItem = setStorageItem.bind(null, 'sessionStorage')

export const getLocalStorageItem = getStorageItem.bind(null, 'localStorage')

export const setLocalStorageItem = setStorageItem.bind(null, 'localStorage')

// tree数据转换
export function transformDataListToTree (list, idName = 'id', parentIdName = 'parentId') {
  const rootId = 0
  const map = {}
  const roots = []
  list.sort((a, b) => {
    if (a[idName] === b[idName]) {
      return 0
    }
    return a[idName] > b[idName] ? 1 : -1
  }).forEach((item, idx) => {
    map[list[idx][idName]] = idx
    item.children = []
    item.__id = 'id_' + Math.random() + Date.now()
  })
  list.forEach((item) => {
    if ([rootId, null, undefined, ''].indexOf(item[parentIdName]) !== -1) {
      item.tIndex = 0
      roots.push(item)
    } else {
      const parent = list[map[item[parentIdName]]]
      item.__parentId = parent.__id
      parent.children.push(item)
    }
  })
  return roots
}
